/**
 * Copyright 2011, Under-Ground Studio.
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.edu.zju.vlis.aus;

import android.app.Activity;
import android.app.ActivityGroup;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;
import cn.edu.zju.vlis.aus.activity.ChartActivity;
import cn.edu.zju.vlis.aus.activity.SettingActivity;
import cn.edu.zju.vlis.aus.activity.UnusedActivity;
import cn.edu.zju.vlis.aus.activity.UsedRankActivity;
import cn.edu.zju.vlis.aus.db.UsageRecordDAO;
import cn.edu.zju.vlis.aus.service.LogcatAnalyzeService;
import cn.edu.zju.vlis.aus.service.LogcatAnalyzeService.LogcatAnalyzeBinder;
import cn.edu.zju.vlis.aus.service.LogcatAnalyzer;
import cn.edu.zju.vlis.aus.util.PreferenceHelper;

import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import com.google.ads.AdRequest.ErrorCode;

/**
 * Instance of this class in an activity group that contains all the activities
 * of this application.
 * 
 * @author ymsong (songyuming1985@gmail.com) 2011-9-26
 */
public class MainActivity extends ActivityGroup implements OnTabChangeListener,
		OnClickListener {
	private static final String TAB_USED_RANK = "tab1";
	private static final String TAB_UNUSED = "tab2";
	private static final String TAB_CHART = "tab3";
	private static final String TAB_SETTING = "tab4";

	// sub views
	private TabHost tabHost;
	private TabWidget tabWidget;
	private TextView title;
	private int preTab;
	// ad views
	private AdView adView;
	private Button btnClose;
	private boolean adClosed;

	// services
	private LogcatAnalyzeService logcatService;
	private boolean serviceBound;
	private ServiceConnection serviceConnection = new LAServiceConnection();

	private UsageRecordDAO dao;
	private LogcatAnalyzer analyzer;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// create the sub views
		title = (TextView) findViewById(R.id.title_text);
		setTitle(R.string.title_used_rank);

		tabHost = (TabHost) findViewById(R.id.tabhost);
		tabHost.setup(getLocalActivityManager());
		tabWidget = tabHost.getTabWidget();

		TabSpec tabUsedRank = createTabSpec(TAB_USED_RANK,
				R.drawable.tab_used_rank, R.string.tab_used_rank,
				UsedRankActivity.class);
		tabHost.addTab(tabUsedRank);
		TabSpec tabUnused = createTabSpec(TAB_UNUSED, R.drawable.tab_unused,
				R.string.tab_unused, UnusedActivity.class);
		tabHost.addTab(tabUnused);
		TabSpec tabChart = createTabSpec(TAB_CHART, R.drawable.tab_chart,
				R.string.tab_chart, ChartActivity.class);
		tabHost.addTab(tabChart);
		TabSpec tabSetting = createTabSpec(TAB_SETTING, R.drawable.tab_setting,
				R.string.tab_setting, SettingActivity.class);
		tabHost.addTab(tabSetting);

		tabHost.setOnTabChangedListener(this);
		tabHost.setCurrentTab(0);
		tabWidget.getChildAt(0).setBackgroundResource(
				R.drawable.tab_item_selected_bg);
		preTab = 0;

		dao = new UsageRecordDAO(this);
		// adview
		adView = (AdView) findViewById(R.id.ad_view);
		adView.setAdListener(new MyAdListener());
		adView.setVisibility(View.GONE);
		adView.loadAd(new AdRequest());
		btnClose = (Button) findViewById(R.id.btn_close_ad);
		btnClose.setOnClickListener(this);
		btnClose.setVisibility(View.GONE);
	}

	private TabSpec createTabSpec(String tag, int imageRes, int textRes,
			Class<? extends Activity> targetActivity) {
		RelativeLayout tabIndicator = (RelativeLayout) LayoutInflater
				.from(this).inflate(R.layout.tab_indicator, null);
		ImageView image = (ImageView) tabIndicator.findViewById(R.id.icon);
		image.setImageResource(imageRes);
		TextView tv = (TextView) tabIndicator.findViewById(R.id.title);
		tv.setText(textRes);
		Intent intent = new Intent(MainActivity.this, targetActivity);
		TabSpec tabSpec = tabHost.newTabSpec(tag);
		tabSpec.setIndicator(tabIndicator);
		tabSpec.setContent(intent);
		return tabSpec;
	}

	@Override
	protected void onStart() {
		super.onStart();
		boolean shouldRunService = PreferenceHelper.isServiceRunning(this);
		if (shouldRunService) {
			startLogcatService();
		}
		scanAndRefreshData();
	}

	@Override
	protected void onStop() {
		if (serviceBound) {
			unbindService(serviceConnection);
			serviceBound = false;
		}
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		dao.close();
		super.onDestroy();
	}

	@Override
	public void onTabChanged(String arg0) {
		int currentTab = tabHost.getCurrentTab();
		tabWidget.getChildAt(preTab).setBackgroundDrawable(null);
		tabWidget.getChildAt(currentTab).setBackgroundResource(
				R.drawable.tab_item_selected_bg);
		preTab = currentTab;
		refreshTitle(currentTab);
		if (!adClosed) {
			new AdViewTask().execute();
		}
	}

	@Override
	public void onClick(View v) {
		if (v == btnClose) {
			adView.setVisibility(View.GONE);
			btnClose.setVisibility(View.GONE);
			adClosed = true;
		}
	}

	private void refreshTitle(int currentTab) {
		switch (currentTab) {
		case 0:
			getUsedRankActivity().setTitleWithCount();
			break;
		case 1:
			getUnusedActivity().setTitleWithCount();
			break;
		case 2:
			String[] charts = getResources().getStringArray(
					R.array.title_statistical_chart);
			int curItem = getChartActivity().getCurrentItem();
			setTitle(charts[curItem]);
			break;
		case 3:
			setTitle(R.string.title_setting);
			break;
		}
	}

	public void setTitle(int resId) {
		title.setText(resId);
	}

	@Override
	public void setTitle(CharSequence text) {
		title.setText(text);
	}

	private UsedRankActivity getUsedRankActivity() {
		return (UsedRankActivity) getLocalActivityManager().getActivity(
				TAB_USED_RANK);
	}

	private UnusedActivity getUnusedActivity() {
		return (UnusedActivity) getLocalActivityManager().getActivity(
				TAB_UNUSED);
	}

	private ChartActivity getChartActivity() {
		return (ChartActivity) getLocalActivityManager().getActivity(TAB_CHART);
	}

	public SettingActivity getSettingActivity() {
		return (SettingActivity) getLocalActivityManager().getActivity(
				TAB_SETTING);
	}

	public void scanAndRefreshData() {
		if (analyzer == null) {
			analyzer = new LogcatAnalyzer(dao);
		}
		analyzer.analyze(this);
		UsedRankActivity usedRank = getUsedRankActivity();
		if (usedRank != null) {
			usedRank.refresh();
		}
		UnusedActivity unused = getUnusedActivity();
		if (unused != null) {
			unused.refresh();
		}
		ChartActivity chart = getChartActivity();
		if (chart != null) {
			chart.refresh();
		}
		SettingActivity setting = getSettingActivity();
		if (setting != null) {
			setting.refresh();
		}
		int currentTab = tabHost.getCurrentTab();
		refreshTitle(currentTab);
	}

	public void refreshForAppFilter() {
		UsedRankActivity usedRank = getUsedRankActivity();
		if (usedRank != null) {
			usedRank.refresh();
		}
		UnusedActivity unused = getUnusedActivity();
		if (unused != null) {
			unused.refresh();
		}
		ChartActivity chart = getChartActivity();
		if (chart != null) {
			chart.refresh();
		}
		int currentTab = tabHost.getCurrentTab();
		refreshTitle(currentTab);
	}

	/**
	 * @author ymsong (songyuming1985@gmail.com) 2011-8-4
	 */
	public class LAServiceConnection implements ServiceConnection {

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			LogcatAnalyzeBinder binder = (LogcatAnalyzeBinder) service;
			logcatService = binder.getService();
			serviceBound = true;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			serviceBound = false;
		}
	}

	public void startLogcatService() {
		Intent intent = new Intent(this, LogcatAnalyzeService.class);
		if (LogcatAnalyzeService.instanceCount == 0) {
			startService(intent);
		}
		bindService(intent, serviceConnection, 0);
	}

	public void stopLogcatService() {
		if (logcatService != null) {
			logcatService.requestStop();
		}
	}

	private final class MyAdListener implements AdListener {
		@Override
		public void onReceiveAd(Ad arg0) {
			if (!adClosed){
				adView.setVisibility(View.VISIBLE);
				btnClose.setVisibility(View.VISIBLE);	
			}
		}
		
	
		@Override
		public void onFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
//			adView.setVisibility(View.GONE);
//			btnClose.setVisibility(View.GONE);
		}
	
		@Override
		public void onPresentScreen(Ad arg0) {
		}
	
		@Override
		public void onLeaveApplication(Ad arg0) {
		}
	
		@Override
		public void onDismissScreen(Ad arg0) {
		}
	}

	private class AdViewTask extends AsyncTask<Void, Void, Void> {

		private static final int ADVIEW_DELAY = 3000;

		@Override
		protected void onPreExecute() {
			adView.setVisibility(View.GONE);
			btnClose.setVisibility(View.GONE);
		}

		@Override
		protected Void doInBackground(Void... params) {
			try {
				Thread.sleep(ADVIEW_DELAY);
			} catch (InterruptedException e) {
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			adView.loadAd(new AdRequest());
		}
	}

}